import tkinter as tk
from tkinter import ttk, messagebox
import json
import math
import re
import time
import relog as rl
from collections import defaultdict
from data_loader import data,get_base_materials, save_base_materials, validate_material_ids, id_to_name, all_item_ids, get_crafting_helper, base_materials
from settings_applier import apply_settings

class CraftingCalculator:
    """共享的合成计算功能"""
    
    @staticmethod
    def calculate_materials(item_quantities):
        """计算多个物品所需的基础材料"""
        crafting_helper = get_crafting_helper()
        if not crafting_helper:
            return None, "合成助手未初始化"
        
        try:
            # 构建需求列表
            demands = [{"item": item_id, "count": count} for item_id, count in item_quantities.items()]
            result = crafting_helper.solve(demands, base_materials)
            return result, None
        except Exception as e:
            return None, f"计算材料时出错: {str(e)}"
    
    @staticmethod
    def format_material_list(result, item_quantities):
        """格式化材料列表输出"""
        # 合并相同材料
        material_dict = defaultdict(float)
        for mat in result.get("basicMaterial", []):
            material_dict[mat["item"]] += mat["count"]
        
        # 构建结果字符串
        material_list = []
        total_items = 0
        
        for mat_id, amount in material_dict.items():
            mat_name = id_to_name.get(mat_id, mat_id)
            rounded_amount = math.ceil(amount)
            material_list.append((mat_name, mat_id, rounded_amount))
            total_items += rounded_amount
        
        # 按材料名称排序
        material_list.sort(key=lambda x: x[0])
        
        # 构建标题
        title_parts = []
        for item_id, count in item_quantities.items():
            item_name = id_to_name.get(item_id, item_id)
            title_parts.append(f"{count}个{item_name}")
        
        title = "制作 " + " + ".join(title_parts) + " 所需的基础材料:"
        
        # 构建详细内容
        result_lines = [title]
        result_lines.append(f"总共需要 {len(material_list)} 种基础材料，合计 {total_items} 个物品\n")
        
        for index, (mat_name, mat_id, amount) in enumerate(material_list, 1):
            formatted_amount = CraftingCalculator.format_quantity(amount)
            if mat_name == mat_id:
                result_lines.append(f"[{index}]. {mat_name}: {formatted_amount}")
            else:
                result_lines.append(f"[{index}]. {mat_name} ({mat_id}): {formatted_amount}")
        
        return "\n".join(result_lines)
    
    @staticmethod
    def format_quantity(quantity):
        """格式化数量显示"""
        if quantity < 64:
            return str(quantity)
        
        groups = quantity // 64
        remainder = quantity % 64
        
        if remainder == 0:
            return f"{groups}*64"
        else:
            return f"{groups}*64+{remainder}"

    @staticmethod
    def format_crafting_steps(result, item_quantities):
        """格式化合成步骤输出"""
        output_lines = []
        
        # 添加标题 - 显示所有选中的物品
        title_parts = []
        for item_id, count in item_quantities.items():
            item_name = id_to_name.get(item_id, item_id)
            title_parts.append(f"{count}个{item_name}")
        
        output_lines.append("制作 " + " + ".join(title_parts) + " 的合成步骤:\n")
        
        # 基础材料部分
        if result.get("basicMaterial"):
            output_lines.append("\n基础材料:")
            sorted_materials = sorted(
                result["basicMaterial"],
                key=lambda x: id_to_name.get(x["item"], x["item"])
            )
            for index, item in enumerate(sorted_materials, 1):
                mat_name = id_to_name.get(item["item"], item["item"])
                count = math.ceil(item['count'])
                formatted_count = CraftingCalculator.format_quantity(count)
                output_lines.append(f"[{index}]. {mat_name} × {formatted_count}")
        else:
            output_lines.append("\n无基础材料")
        
        # 合成路线部分
        output_lines.append("\n合成步骤:")
        if result.get("madeRoute"):
            steps = []
            for route in result["madeRoute"]:
                materials = []
                for item, count in route["materialList"]:
                    mat_name = id_to_name.get(item, item)
                    formatted_count = CraftingCalculator.format_quantity(math.ceil(count))
                    materials.append(f"{mat_name} × {formatted_count}")
                
                product_name = id_to_name.get(route["product"], route["product"])
                product_count = CraftingCalculator.format_quantity(math.ceil(route["productCount"]))
                steps.append(f"{' + '.join(materials)} ==({route['machine']})=> {product_name} × {product_count}")
            
            # 逆序显示步骤
            for i, step in enumerate(reversed(steps), 1):
                output_lines.append(f"[{i}]. {step}")
        else:
            output_lines.append("无合成步骤（直接获取或基础材料）")
        
        # 剩余材料部分 - 剔除计划内需要的产物
        excess_materials = defaultdict(float)
        if result.get("extraItem"):
            for item in result["extraItem"]:
                excess_materials[item["item"]] += item["count"]
        
        # 从剩余材料中剔除计划内需要的产物
        for item_id, count in item_quantities.items():
            if item_id in excess_materials:
                # 如果剩余材料中有这个物品，减去计划需要的数量
                excess_materials[item_id] -= count
                # 如果减完后小于等于0，则从剩余材料中移除
                if excess_materials[item_id] <= 0:
                    del excess_materials[item_id]
        
        if excess_materials:
            output_lines.append("\n剩余材料:")
            for mat_id, count in excess_materials.items():
                mat_name = id_to_name.get(mat_id, mat_id)
                formatted_count = CraftingCalculator.format_quantity(math.ceil(count))
                output_lines.append(f"{mat_name} × {formatted_count}")
        else:
            output_lines.append("\n无剩余材料")
        
        return "\n".join(output_lines)


class BaseMaterialEditor(tk.Toplevel):
    """独立的基础材料编辑组件"""
    
    def __init__(self, parent, refresh_callback=None,settings=None):
        super().__init__(parent)
        self.title("编辑基础材料名单")
        self.geometry("700x650")
        self.refresh_callback = refresh_callback
        self.settings = settings or {}
        self.apply_settings(self.settings)
        
        # 导入主菜单数据
        self.data = data
        
        self.create_widgets()
        self.load_materials()
        
        # 绑定关闭事件
        self.protocol("WM_DELETE_WINDOW", self.on_close)
        rl.write("sra.log", "base_material_editor:基础材料编辑器已打开")
    
    def apply_settings(self, settings):
        """应用设置到当前窗口"""
        apply_settings(self, settings)

    def create_widgets(self):
        """创建界面组件"""
        main_frame = ttk.Frame(self)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 标题和说明
        header_frame = ttk.Frame(main_frame)
        header_frame.pack(fill=tk.X, pady=5)
        
        ttk.Label(
            header_frame, 
            text="基础材料名单管理", 
            font=("", 12, "bold")
        ).pack(pady=5)
        
        ttk.Label(
            header_frame, 
            text="在此名单中的材料将被视为基础材料，计算材料时不会进一步展开配方",
            wraplength=600
        ).pack(pady=2)
        
        # 搜索和过滤区域
        filter_frame = ttk.Frame(main_frame)
        filter_frame.pack(fill=tk.X, pady=5)
        
        ttk.Label(filter_frame, text="过滤材料:").pack(side=tk.LEFT, padx=(0, 5))
        
        self.filter_var = tk.StringVar()
        self.filter_entry = ttk.Entry(filter_frame, textvariable=self.filter_var, width=30)
        self.filter_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
        self.filter_entry.bind("<KeyRelease>", self.filter_materials)
        
        # 材料列表区域
        list_frame = ttk.LabelFrame(main_frame, text="基础材料名单")
        list_frame.pack(fill=tk.BOTH, expand=True, pady=5)
        
        # 列表和滚动条
        self.tree = ttk.Treeview(list_frame, columns=("name", "id"), show="headings", selectmode="extended")
        self.tree.heading("name", text="物品名称")
        self.tree.heading("id", text="ID")
        self.tree.column("name", width=250, anchor="w")
        self.tree.column("id", width=150, anchor="w")
        
        vsb = ttk.Scrollbar(list_frame, orient="vertical", command=self.tree.yview)
        hsb = ttk.Scrollbar(list_frame, orient="horizontal", command=self.tree.xview)
        self.tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
        
        self.tree.grid(row=0, column=0, sticky="nsew")
        vsb.grid(row=0, column=1, sticky="ns")
        hsb.grid(row=1, column=0, sticky="ew")
        
        # 配置网格布局
        list_frame.columnconfigure(0, weight=1)
        list_frame.rowconfigure(0, weight=1)
        
        # 添加右键菜单
        self.context_menu = tk.Menu(self, tearoff=0)
        self.context_menu.add_command(label="移除选中材料", command=self.remove_selected)
        self.tree.bind("<Button-3>", self.show_context_menu)
        
        # 按钮区域
        btn_frame = ttk.Frame(main_frame)
        btn_frame.pack(fill=tk.X, pady=10)
        
        ttk.Button(
            btn_frame, 
            text="添加材料", 
            command=self.add_material
        ).pack(side=tk.LEFT, padx=5)
        
        ttk.Button(
            btn_frame, 
            text="保存", 
            command=self.save_materials,
            style="Accent.TButton"
        ).pack(side=tk.RIGHT, padx=5)
        
        ttk.Button(
            btn_frame, 
            text="取消", 
            command=self.destroy
        ).pack(side=tk.RIGHT, padx=5)
    
    def load_materials(self):
        """加载当前基础材料名单"""
        self.materials = sorted(get_base_materials())
        self.filtered_materials = self.materials.copy()
        self.update_list()
        rl.write("sra.log", f"base_material_editor:已加载 {len(self.materials)} 个基础材料")
    
    def update_list(self):
        """更新列表显示"""
        # 清除当前列表
        for item in self.tree.get_children():
            self.tree.delete(item)
        
        # 添加材料
        for mat_id in self.filtered_materials:
            name = id_to_name.get(mat_id, "未知物品")
            self.tree.insert("", "end", values=(name, mat_id))
    
    def filter_materials(self, event=None):
        """根据过滤条件筛选材料"""
        filter_text = self.filter_var.get().lower()
        
        if not filter_text:
            self.filtered_materials = self.materials.copy()
        else:
            self.filtered_materials = [
                mat_id for mat_id in self.materials
                if filter_text in mat_id.lower() or 
                   filter_text in id_to_name.get(mat_id, "").lower()
            ]
        
        self.update_list()
        rl.write("sra.log", f"base_material_editor:过滤材料 - 条件: '{filter_text}', 结果: {len(self.filtered_materials)}")
    
    def show_context_menu(self, event):
        """显示右键菜单"""
        item = self.tree.identify_row(event.y)
        if item:
            self.tree.selection_set(item)
            self.context_menu.post(event.x_root, event.y_root)
    
    def remove_selected(self):
        """移除选中的材料"""
        selected = self.tree.selection()
        if not selected:
            return
        
        selected_ids = [self.tree.item(i, "values")[1] for i in selected]
        self.materials = [mat_id for mat_id in self.materials if mat_id not in selected_ids]
        self.filtered_materials = [mat_id for mat_id in self.filtered_materials if mat_id not in selected_ids]
        self.update_list()
        rl.write("sra.log", f"base_material_editor:已移除 {len(selected_ids)} 个材料")
    
    def add_material(self):
        """添加新材料到名单"""
        add_win = tk.Toplevel(self)
        add_win.title("添加基础材料")
        add_win.geometry("500x400")
        add_win.transient(self)
        add_win.grab_set()
        
        main_frame = ttk.Frame(add_win)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 搜索区域
        search_frame = ttk.Frame(main_frame)
        search_frame.pack(fill=tk.X, pady=5)
        
        ttk.Label(search_frame, text="搜索物品:").pack(side=tk.LEFT, padx=(0, 5))
        
        self.search_var = tk.StringVar()
        search_entry = ttk.Entry(search_frame, textvariable=self.search_var, width=30)
        search_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
        search_entry.bind("<KeyRelease>", lambda e: self.filter_add_items(add_win))
        
        # 物品列表区域
        list_frame = ttk.LabelFrame(main_frame, text="所有物品（未添加的）")
        list_frame.pack(fill=tk.BOTH, expand=True, pady=5)
        
        # 创建列表
        self.item_tree = ttk.Treeview(list_frame, columns=("name", "id"), show="headings", selectmode="browse")
        self.item_tree.heading("name", text="物品名称")
        self.item_tree.heading("id", text="ID")
        self.item_tree.column("name", width=250, anchor="w")
        self.item_tree.column("id", width=150, anchor="w")
        
        vsb = ttk.Scrollbar(list_frame, orient="vertical", command=self.item_tree.yview)
        hsb = ttk.Scrollbar(list_frame, orient="horizontal", command=self.item_tree.xview)
        self.item_tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
        
        self.item_tree.grid(row=0, column=0, sticky="nsew")
        vsb.grid(row=0, column=1, sticky="ns")
        hsb.grid(row=1, column=0, sticky="ew")
        
        # 配置网格布局
        list_frame.columnconfigure(0, weight=1)
        list_frame.rowconfigure(0, weight=1)
        
        # 填充物品列表
        self.filter_add_items(add_win)
        
        # 添加按钮区域
        btn_frame = ttk.Frame(main_frame)
        btn_frame.pack(fill=tk.X, pady=10)
        
        ttk.Button(
            btn_frame, 
            text="添加选中材料", 
            command=lambda: self.add_selected_item(add_win),
            width=15
        ).pack(side=tk.LEFT, padx=5)
        
        # 状态显示区域
        self.status_label = ttk.Label(main_frame, text="", foreground="red")
        self.status_label.pack(pady=5)
    
    def filter_add_items(self, window):
        """根据搜索词过滤物品列表，只显示未添加的物品，并按主菜单顺序"""
        search_term = self.search_var.get().lower()
        
        # 清除当前列表
        for item in self.item_tree.get_children():
            self.item_tree.delete(item)
        
        # 按照主菜单的顺序添加匹配项（只显示未添加的物品）
        for item in self.data:
            mat_id = item["id"]
            # 如果物品已在基础材料中，跳过不显示
            if mat_id in self.materials:
                continue
                
            name = id_to_name.get(mat_id, mat_id)
            
            # 在名称和ID中搜索
            if not search_term or search_term in name.lower() or search_term in mat_id.lower():
                self.item_tree.insert("", "end", 
                                    values=(name, mat_id), 
                                    iid=mat_id)
    
    def add_selected_item(self, window):
        """添加选中的物品到基础材料名单"""
        selected = self.item_tree.focus()
        if not selected:
            self.status_label.config(text="请先选择一个物品")
            return
        
        # 获取选中的物品ID
        mat_id = selected
        
        # 添加新材料
        self.materials.append(mat_id)
        self.materials.sort()
        
        # 更新过滤列表
        filter_text = self.filter_var.get().lower()
        if not filter_text or filter_text in mat_id.lower() or filter_text in id_to_name.get(mat_id, "").lower():
            self.filtered_materials.append(mat_id)
            self.filtered_materials.sort()
        
        # 更新主列表
        self.update_list()
        
        # 更新添加窗口中的列表（移除刚刚添加的物品）
        self.filter_add_items(window)
        
        # 显示成功消息
        name = id_to_name.get(mat_id, mat_id)
        self.status_label.config(text=f"已添加: {name}", foreground="green")
        rl.write("sra.log", f"base_material_editor:已添加新材料: {mat_id}")
    
    def save_materials(self):
        """保存基础材料名单"""
        success, error = save_base_materials(self.materials)
        
        if success:
            messagebox.showinfo("保存成功", "基础材料名单已更新")
            if self.refresh_callback:
                self.refresh_callback()
            self.destroy()
            rl.write("sra.log", "base_material_editor:基础材料名单已保存并关闭编辑器")
        else:
            messagebox.showerror("保存失败", f"保存文件时出错:\n{error}")
            rl.write("sra.log", f"base_material_editor:保存材料名单失败: {error}")
    
    def on_close(self):
        """窗口关闭时的处理"""
        if self.materials != get_base_materials():
            if messagebox.askyesno("未保存的更改", "您有未保存的更改，是否保存？"):
                self.save_materials()
            else:
                rl.write("sra.log", "base_material_editor:取消编辑并关闭编辑器")
                self.destroy()
        else:
            rl.write("sra.log", "base_material_editor:无更改并关闭编辑器")
            self.destroy()

class MultiItemCalculator(tk.Toplevel):
    """多物品材料计算器"""
    def __init__(self, parent,settings=None):
        super().__init__(parent)
        self.title("多物品材料计算器")
        self.geometry("800x750")
        self.item_quantities = {}
        self.settings = settings or {}
        self.apply_settings(self.settings)
        
        # 导入主菜单数据
        self.data = data
        
        self.create_widgets()
        self.update_item_list()
        
        # 绑定关闭事件
        self.protocol("WM_DELETE_WINDOW", self.on_close)
    
    def apply_settings(self, settings):
        """应用设置到当前窗口"""
        apply_settings(self, settings)
        
    def create_widgets(self):
        """创建界面组件"""
        main_frame = ttk.Frame(self)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 物品选择区域
        selection_frame = ttk.LabelFrame(main_frame, text="选择要计算的物品")
        selection_frame.pack(fill=tk.X, pady=5)
        
        # 搜索和添加区域
        search_frame = ttk.Frame(selection_frame)
        search_frame.pack(fill=tk.X, pady=5)
        
        ttk.Label(search_frame, text="搜索物品:").pack(side=tk.LEFT, padx=(0, 5))
        
        self.search_var = tk.StringVar()
        search_entry = ttk.Entry(search_frame, textvariable=self.search_var, width=30)
        search_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
        search_entry.bind("<KeyRelease>", self.filter_items)
        
        # 物品列表
        list_frame = ttk.Frame(selection_frame)
        list_frame.pack(fill=tk.BOTH, expand=True, pady=5)
        
        self.item_tree = ttk.Treeview(list_frame, columns=("name", "id"), show="headings", selectmode="browse")
        self.item_tree.heading("name", text="物品名称")
        self.item_tree.heading("id", text="ID")
        self.item_tree.column("name", width=300, anchor="w")
        self.item_tree.column("id", width=200, anchor="w")
        
        vsb = ttk.Scrollbar(list_frame, orient="vertical", command=self.item_tree.yview)
        hsb = ttk.Scrollbar(list_frame, orient="horizontal", command=self.item_tree.xview)
        self.item_tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
        
        self.item_tree.grid(row=0, column=0, sticky="nsew")
        vsb.grid(row=0, column=1, sticky="ns")
        hsb.grid(row=1, column=0, sticky="ew")
        
        # 配置网格布局
        list_frame.columnconfigure(0, weight=1)
        list_frame.rowconfigure(0, weight=1)
        
        # 数量输入和添加按钮
        add_frame = ttk.Frame(selection_frame)
        add_frame.pack(fill=tk.X, pady=5)
        
        ttk.Label(add_frame, text="数量:").pack(side=tk.LEFT, padx=(0, 5))
        
        self.quantity_var = tk.StringVar(value="1")
        quantity_entry = ttk.Entry(add_frame, textvariable=self.quantity_var, width=10)
        quantity_entry.pack(side=tk.LEFT, padx=(0, 10))
        
        ttk.Button(
            add_frame, 
            text="添加到计算列表", 
            command=self.add_item_to_calculation
        ).pack(side=tk.LEFT)
        
        # 已选物品区域
        selected_frame = ttk.LabelFrame(main_frame, text="已选物品")
        selected_frame.pack(fill=tk.BOTH, expand=True, pady=5)
        
        # 已选物品列表
        self.selected_tree = ttk.Treeview(selected_frame, columns=("name", "id", "quantity"), show="headings")
        self.selected_tree.heading("name", text="物品名称")
        self.selected_tree.heading("id", text="ID")
        self.selected_tree.heading("quantity", text="数量")
        self.selected_tree.column("name", width=250)
        self.selected_tree.column("id", width=150)
        self.selected_tree.column("quantity", width=80)
        
        vsb2 = ttk.Scrollbar(selected_frame, orient="vertical", command=self.selected_tree.yview)
        hsb2 = ttk.Scrollbar(selected_frame, orient="horizontal", command=self.selected_tree.xview)
        self.selected_tree.configure(yscrollcommand=vsb2.set, xscrollcommand=hsb2.set)
        
        self.selected_tree.grid(row=0, column=0, sticky="nsew")
        vsb2.grid(row=0, column=1, sticky="ns")
        hsb2.grid(row=1, column=0, sticky="ew")
        
        # 配置网格布局
        selected_frame.columnconfigure(0, weight=1)
        selected_frame.rowconfigure(0, weight=1)
        
        # 添加右键菜单
        self.context_menu = tk.Menu(self, tearoff=0)
        self.context_menu.add_command(label="移除选中物品", command=self.remove_selected_item)
        self.selected_tree.bind("<Button-3>", self.show_context_menu)
        
        # 按钮区域
        btn_frame = ttk.Frame(main_frame)
        btn_frame.pack(fill=tk.X, pady=10)
        
        ttk.Button(
            btn_frame, 
            text="计算材料", 
            command=self.calculate_materials,
            style="Accent.TButton"
        ).pack(side=tk.LEFT, padx=5)
        
        ttk.Button(
            btn_frame, 
            text="计算合成步骤", 
            command=self.calculate_steps,
            style="Accent.TButton"
        ).pack(side=tk.LEFT, padx=5)
        
        ttk.Button(
            btn_frame, 
            text="清空列表", 
            command=self.clear_list
        ).pack(side=tk.LEFT, padx=5)
        
        ttk.Button(
            btn_frame, 
            text="关闭", 
            command=self.destroy
        ).pack(side=tk.RIGHT, padx=5)
        
        # 初始填充物品列表
        self.filter_items()
    
    def filter_items(self, event=None):
        filter_text = self.search_var.get().lower()
        
        # 清除当前列表
        for item in self.item_tree.get_children():
            self.item_tree.delete(item)
        
        # 按照主菜单的顺序添加匹配项
        for item in self.data:
            item_id = item["id"]
            name = item["name"]
            
            # 在名称和ID中搜索
            if not filter_text or filter_text in name.lower() or filter_text in item_id.lower():
                self.item_tree.insert("", "end", values=(name, item_id), iid=item_id)
    
    def add_item_to_calculation(self):
        """添加物品到计算列表"""
        selected = self.item_tree.focus()
        if not selected:
            messagebox.showwarning("警告", "请先选择一个物品")
            return
        
        # 获取数量
        try:
            quantity = int(self.quantity_var.get())
            if quantity < 1:
                raise ValueError("数量必须大于0")
        except ValueError:
            messagebox.showwarning("输入错误", "数量必须是正整数")
            return
        
        # 获取物品ID和名称
        item_id = selected
        item_name = id_to_name.get(item_id, item_id)
        
        # 添加到计算列表
        if item_id in self.item_quantities:
            self.item_quantities[item_id] += quantity
        else:
            self.item_quantities[item_id] = quantity
        
        # 更新列表显示
        self.update_item_list()
    
    def update_item_list(self):
        """更新已选物品列表"""
        # 清除当前列表
        for item in self.selected_tree.get_children():
            self.selected_tree.delete(item)
        
        # 添加物品
        for item_id, quantity in self.item_quantities.items():
            item_name = id_to_name.get(item_id, item_id)
            self.selected_tree.insert("", "end", values=(item_name, item_id, quantity), iid=item_id)
    
    def show_context_menu(self, event):
        """显示右键菜单"""
        item = self.selected_tree.identify_row(event.y)
        if item:
            self.selected_tree.selection_set(item)
            self.context_menu.post(event.x_root, event.y_root)
    
    def remove_selected_item(self):
        """移除选中的物品"""
        selected = self.selected_tree.selection()
        if not selected:
            return
        
        for item_id in selected:
            if item_id in self.item_quantities:
                del self.item_quantities[item_id]
        
        self.update_item_list()
    
    def clear_list(self):
        """清空已选物品列表"""
        self.item_quantities = {}
        self.update_item_list()
    
    def calculate_materials(self):
        """计算所需材料"""
        if not self.item_quantities:
            messagebox.showwarning("警告", "请先添加要计算的物品")
            return
        
        # 使用共享的计算功能
        result, error = CraftingCalculator.calculate_materials(self.item_quantities)
        
        if error:
            messagebox.showerror("错误", error)
            return
        
        if not result.get("basicMaterial"):
            messagebox.showinfo("无基础材料", "所选物品不需要任何基础材料")
            return
        
        # 格式化结果
        result_text = CraftingCalculator.format_material_list(result, self.item_quantities)
        
        # 显示结果
        from item_detail_window import TextResultWindow
        TextResultWindow(
            self,
            "材料计算结果",
            result_text,
            "材料计算结果",
            settings=self.settings
        )
    
    def calculate_steps(self):
        """计算合成步骤"""
        if not self.item_quantities:
            messagebox.showwarning("警告", "请先添加要计算的物品")
            return
        
        # 使用共享的计算功能
        result, error = CraftingCalculator.calculate_materials(self.item_quantities)
        
        if error:
            messagebox.showerror("错误", error)
            return
        
        # 格式化结果
        result_text = CraftingCalculator.format_crafting_steps(result, self.item_quantities)
        
        # 显示结果
        from item_detail_window import TextResultWindow
        TextResultWindow(
            self,
            "合成步骤结果",
            result_text,
            "合成步骤结果",
            settings=self.settings
        )
    
    def on_close(self):
        """窗口关闭时的处理"""
        self.destroy()